#include "music.h"

#include <QUuid>
#include <QMediaPlayer>
#include <QDebug>
#include <QApplication>
#include <QSqlQuery>
#include <QSqlError>

Music::Music()
    :isLike(false)
    ,isHistory(false)
{

}

Music::Music(QUrl url)
    :isLike(false)
    ,isHistory(false)
    ,musicUrl(url)
{
    this->musicId = QUuid::createUuid().toString();
    parseMediaMetaMusic();
}

void Music::setMusicId(const QString &musicId)
{
    this->musicId = musicId;
}

void Music::setMusicName(const QString &musicName)
{
    this->musicName = musicName;
}

void Music::setMusicSinger(const QString &musicSinger)
{
    this->musicSinger = musicSinger;
}

void Music::setMusicAlbumn(const QString &musicAlbumn)
{
    this->musicAlbum = musicAlbumn;
}

void Music::setMusicTime(uint64_t musicTime)
{
    this->musicTime = musicTime;
}

void Music::setIsLike(bool isLike)
{
    this->isLike = isLike;
}

void Music::setIsHistory(bool isHistory)
{
    this->isHistory = isHistory;
}

void Music::setMusicUrl(QUrl musicUrl)
{
    this->musicUrl = musicUrl;
}

QString Music::getMusicName() const
{
    return this->musicName;
}

QString Music::getMusicSinger() const
{
    return this->musicSinger;
}

QString Music::getMusicAlbumn() const
{
    return this->musicAlbum;
}

uint64_t Music::getMusicTime() const
{
    return this->musicTime;
}

bool Music::getIsLike() const
{
    return this->isLike;
}

bool Music::getIsHistory() const
{
    return this->isHistory;
}

QUrl Music::getMusicUrl() const
{
    return this->musicUrl;
}

QString Music::getMusicId()
{
    return musicId;
}

QString Music::getMusicLrcPath()
{
    QString lrcPath = musicUrl.toLocalFile();

    lrcPath.replace(".mp3", ".lrc");
    lrcPath.replace(".flac", ".lrc");
    lrcPath.replace(".mpga", ".lrc");

    return lrcPath;
}

void Music::insertMusicToDB()
{
    //检测music在数据库中是否存在
    QSqlQuery query;
    query.prepare("SELECT EXISTS (SELECT 1 FROM MusicInfo WHERE musicId = ?)");
    query.addBindValue(musicId);

    if(!query.exec())
    {
        qDebug() << "查询失败: " << query.lastError().text();
        return;
    }

    if(query.next())
    {
        bool isExists = query.value(0).toBool();
        if(isExists)
        {
            //music存在, 更新music的isLike和isHistory属性

            query.prepare("UPDATE MusicInfo SET isLike = ?, isHistory = ? WHERE musicId = ?");
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory ? 1 : 0);
            query.addBindValue(musicId);

            if(!query.exec())
            {
                qDebug() << "更新失败: " << query.lastError().text();
                return;
            }

            qDebug() << "更新: " << musicName << " " << musicId;
        }
        else
        {
            //music不存在, 插入music
            query.prepare("INSERT INTO MusicInfo(musicId, musicName, musicSinger, musicAlbum, \
                          musicUrl, musicTime, isLike, isHistory) \
                          VALUES(?,?,?,?,?,?,?,?)");
            query.addBindValue(musicId);
            query.addBindValue(musicName);
            query.addBindValue(musicSinger);
            query.addBindValue(musicAlbum);
            query.addBindValue(musicUrl.toLocalFile());
            query.addBindValue(musicTime);
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory ? 1 : 0);

            if(!query.exec())
            {
                qDebug() << "插入失败: " << query.lastError().text();
                return;
            }

            qDebug() << "插入: " << musicName << " " << musicId;
        }
    }
}

void Music::parseMediaMetaMusic()
{
    //创建媒体播放对象
    QMediaPlayer mediaPlayer;

    //通过musicUrl解析源数据
    mediaPlayer.setMedia(musicUrl);

    //setMedia为非阻塞,需要通过isMetaDataAvailable判断解析是否完成
    while(!mediaPlayer.isMetaDataAvailable())
    {
        //执行qt的事件循环
        QCoreApplication::processEvents();
    }

    //解析完成,获取信息
    if(mediaPlayer.isMetaDataAvailable())
    {
        musicName = mediaPlayer.metaData("Title").toString();
        musicSinger = mediaPlayer.metaData("Author").toString();
        musicAlbum = mediaPlayer.metaData("AlbumTitle").toString();
        musicTime = mediaPlayer.metaData("Duration").toLongLong();

        //如果歌名为空
        if(musicName.isEmpty())
        {
            QString fileName = musicUrl.fileName();

            int index = fileName.indexOf('-');

            if(index != -1)
            {
                //"笨小孩(国) - 刘德华.mp3"
                musicName = fileName.mid(0, index).trimmed();
            }
            else
            {
                //"时间你慢些走.mp3"
                musicName = fileName.mid(0, fileName.indexOf('.'));
            }
        }

        //如果歌手为空
        if(musicSinger.isEmpty())
        {
            QString fileName = musicUrl.fileName();

            int index = fileName.indexOf('-');

            if(index != -1)
            {
                musicSinger = fileName.mid(index + 1, fileName.indexOf('.') - index -1).trimmed();
            }
            else
            {
                musicSinger = "未知歌手";
            }
        }

        //如果专辑为空
        if(musicAlbum.isEmpty())
        {
            musicAlbum = "未知专辑";
        }

        qDebug() << musicName << musicSinger << musicAlbum << musicTime;
    }

}
